package com.example.controller;

import com.example.entity.vo.SysUserVo;
import com.example.service.ISysRoleRightService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @ClassName LoginController
 * @description: TODO
 */
@Controller
public class LoginController {

    @Autowired
    ISysRoleRightService sysRoleRightService;

    @RequestMapping("/")
    public String init(){
        return "login";
    }

    @RequestMapping("/doLogin")
    public String login(String usrName, String usrPassword, Model model){

//       String newPassword= new Md5Hash(usrPassword,"czkt",2).toString();
        //创建一个令牌
        UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);

       Subject subject= SecurityUtils.getSubject();

       try {
           subject.login(token);

           SysUserVo user = (SysUserVo) subject.getPrincipal();
           user.getRole().setRights(sysRoleRightService.getRightByUserRoleId(user.getUsrRoleId()));
           subject.getSession().setAttribute("loginUser",user);
       }catch (UnknownAccountException e){
           System.out.println("令牌是假的");
           model.addAttribute("message","账号不存在");
           return "login";
       }catch (LockedAccountException e){
           System.out.println("令牌已过期");
           model.addAttribute("message","账号或密码错误！");
           return "login";
       }catch (AuthenticationException e){
           System.out.println("拿着别的国家的令牌");
           model.addAttribute("message","账号或密码错误！");
           return "login";
       }
       return "main";
    }
    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "login";
    }


    @RequestMapping("/403")
    public String author(){
        return "403";
    }
}
